package pack2_factory;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

interface Human{
    void getColor();
}

class BlackHuman implements Human{

    @Override
    public void getColor() {
        System.out.println("I am a black human");
        
    }
}

class WhiteHuman implements Human{

    @Override
    public void getColor() {
        System.out.println("I am a white human");   
    }
}

class YellowHuman implements Human{

    @Override
    public void getColor() {
        System.out.println("I am a yellow human");   
    }
}

//工厂类：用于生产不同人种，<T extends Human>是返回类型T的泛型修饰符
class HumanFactory<E>{

    // public <E extends Human> void test(){
    //     Human human = (E)new WhiteHuman();
    //     human.getColor();
    // }

    public static <T extends Human> T create_human(Class<T> human_clz){
        Human human = null;
        try{
            
            // Constructor constructor = human_clz.getConstructor();  //获取不到私有无参构造
            Constructor constructor = human_clz.getDeclaredConstructor();  //获取不到私有无参构造
            human = (Human) constructor.newInstance();  
            
            //反射创建实例，并将Object强转为Human
            // human = (Human) Class.forName(human_clz.getName()).newInstance();
        }catch(Exception e){
            e.printStackTrace();
        }
        return (T) human;  //返回类型为T，即强转为子类
    }
}

public class code001_factory{
    public static void main(String[] args) {
        // HumanFactory humanFactory = new HumanFactory();
        // humanFactory.test();

        //生产白人、黑人、黄人，并让他们说话
        Human human1 = HumanFactory.create_human(WhiteHuman.class);
        Human human2 = HumanFactory.create_human(BlackHuman.class);
        Human human3 = HumanFactory.create_human(YellowHuman.class);

        human1.getColor();
        human2.getColor();
        human3.getColor();
    }
}


